<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>订单列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 搜索 -->
        <el-form :inline="true" style="margin-top: 20px;">
            <el-form-item>
                <el-button size="small" @click="exportExcel">导出Excel</el-button>
            </el-form-item>
            <el-form-item>
                <el-input size="small" v-model="mobilev" placeholder="请输入用户手机号"></el-input>
            </el-form-item>
            <el-form-item>
                <el-input size="small" v-model="orderNumberv" placeholder="请输入订单编号"></el-input>
            </el-form-item>
            <el-form-item>
                <el-select size="small" v-model="statusv" placeholder="请选择处理状态">
                    <el-option v-for="item in options" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select size="small" v-model="flagv" placeholder="是否分销订单">
                    <el-option v-for="item in options1" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select size="small" v-model="categoryIdv" placeholder="请选择商品类别">
                    <el-option v-for="item in optionsType" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                创建时间：
                <el-date-picker size="small" v-model="range" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="chongzhi">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 列表 -->
        <el-table size="small" ref="multipleTable" :data="productData" highlight-current-row v-loading="loading" border
            element-loading-text="拼命加载中" style="width: 100%;" v-horizontal-scroll>
            <!-- v-horizontal-scroll="'always'" -->
            <el-table-column align="center" sortable type="index" label="序号" width="75"></el-table-column>
            <el-table-column align="center" sortable prop="distributorsName" label="分销人昵称" width="200" v-if="flagv === 1">
            </el-table-column>
            <el-table-column align="center" sortable prop="commission" label="分销金额" width="200"
                v-if="flagv === 1"></el-table-column>
            <el-table-column align="center" sortable prop="orderNumber" label="订单编号" width="200"></el-table-column>
            <el-table-column align="center" sortable prop="nickName" label="用户昵称" width="100"></el-table-column>
            <el-table-column align="center" sortable prop="mobile" label="用户手机号" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="commodityName" label="商品名" width="100"></el-table-column>
            <el-table-column align="center" sortable prop="categoryName" label="商品类别" width="100"></el-table-column>
            <el-table-column align="center" sortable prop="commodityImage" label="商品封面图" width="120">
                <template slot-scope="scope">
                    <el-image v-if="scope.row.commodityImage != ''" :src="scope.row.commodityImage"
                        :preview-src-list="[scope.row.commodityImage]" style="width: 80px;"></el-image>
                    <div v-if="scope.row.commodityImage == null">没有图片</div>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="freight" label="运费" width="120">
                <template slot-scope="scope">
                    <div>{{ scope.row.freight / 100 }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="buyCount" label="购买数量" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="address" label="地址详情" width="300"></el-table-column>
            <el-table-column align="center" sortable prop="orderPrice" label="订单总额" width="120">
                <template slot-scope="scope">
                    <div>{{ scope.row.orderPrice / 100 }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="payPrice" label="付款总额" width="120">
                <template slot-scope="scope">
                    <div>{{ scope.row.payPrice / 100 }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="priceType" label="价格类型" :formatter="PriceType"
                width="100"></el-table-column>
            <el-table-column align="center" sortable prop="entity" :formatter="isShiti" label="是否实体"
                width="120"></el-table-column>
            <el-table-column sortable prop="status" label="状态" width="120" :formatter="zhuangTai"></el-table-column>
            <el-table-column align="center" sortable prop="remark" label="备注" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="payPoint" label="付款积分" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="orderPoint" label="订单积分" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="shopPrice" label="商品余额价格" width="120">
                <template slot-scope="scope">
                    <div>{{ scope.row.shopPrice / 100 }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="shopPointPrice" label="商品积分价格" width="120"></el-table-column>
            <el-table-column align="center" sortable prop="payTime" label="付款时间" width="150">
                <template slot-scope="scope">
                    <div v-if="transformDate(scope.row.payTime) === '1970-01-01 08:00:00'">没有付款</div>
                    <div v-else>{{ transformDate(scope.row.payTime) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="duration" label="过期时间" width="150">
                <template slot-scope="scope">
                    <div>{{ transformDate(scope.row.duration) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="createTime" label="创建时间" width="150">
                <template slot-scope="scope">
                    <div>{{ transformDate(scope.row.createTime) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" sortable prop="updateTime" label="更新时间" width="150">
                <template slot-scope="scope">
                    <div>{{ transformDate(scope.row.updateTime) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="100" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="tofahuo(scope.row)"
                        v-if="scope.row.status === 1">去发货</el-button>
                    <el-button v-if="scope.row.status === 0" size="mini" type="info" disabled>待支付</el-button>
                    <el-button v-if="scope.row.status === 2" size="mini" type="info" disabled>已发货</el-button>
                    <el-button v-if="scope.row.status === 4" size="mini" type="info" disabled>已关闭</el-button>
                    <el-button v-if="scope.row.status === 3" size="mini" type="info" disabled>已完成</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    </div>
</template>

<script>
import Pagination from '../../components/Pagination'
import {
    getShopOrderList,
    tryPost,
    getCommodityCategoryList
} from "../../api/userMG";
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
export default {
    data() {
        return {
            loading: false,
            productData: [],
            mobilev: '',
            orderNumberv: '',
            statusv: '',
            startTimev: '',
            timestamp: '',
            endTimev: '',
            timestampv: '',
            categoryIdv: '',
            flagv: '',
            options: [{
                value: 0,
                label: '待支付'
            }, {
                value: 1,
                label: '待发货'
            }, {
                value: 2,
                label: '待收货'
            }, {
                value: 3,
                label: '已完成'
            }, {
                value: 4,
                label: '已关闭'
            }],
            options1: [{
                value: 0,
                label: '不是'
            }, {
                value: 1,
                label: '是'
            }],
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            range: [],
            optionsType: [],
            // 分页参数
            pageparm: {
                currentPage: 1,
                pageSize: 20,
                total: 10
            },
        }
    },
    // 注册组件
    components: {
        Pagination
    },
    created() {
        this.getData(1)
        this.gteTypeData()
    },
    watch: {
        range(newRange) {
            this.startTimev = newRange[0];
            this.endTimev = newRange[1];
        }
    },
    methods: {
        exportExcel() {
            let data = {
                mobile: this.mobilev,
                orderNumber: this.orderNumberv,
                status: this.statusv,
                startTime: this.timestamp,
                endTime: this.timestampv,
                categoryId: this.categoryIdv,
                flag: this.flagv,
                page: -2,
            }
            getShopOrderList(data).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.productData = res.data.list;
                    return;
                } else {
                    this.$Message({
                        type: "info",
                        message: res.msg
                    })
                }
            })
            setTimeout(() => {
                //转换成excel时，使用原始的格式
                var xlsxParam = { raw: true };
                let fix = document.querySelector(".el-table__fixed-right");
                let wb;
                //判断有无fixed定位，如果有的话去掉，后面再加上，不然数据会重复
                if (fix) {
                    wb = XLSX.utils.table_to_book(
                        this.$refs.multipleTable.$el.removeChild(fix), xlsxParam
                    );
                    this.$refs.multipleTable.$el.appendChild(fix);
                } else {
                    wb = XLSX.utils.table_to_book(this.$refs.multipleTable.$el, xlsxParam);
                }
                var wbout = XLSX.write(wb, {
                    bookType: "xls",
                    bookSST: true,
                    type: "array",
                });
                try {
                    // 如果是IE浏览器，使用Blob通过navigator.msSaveBlob保存
                    if (navigator.msSaveBlob) {
                        navigator.msSaveBlob(new Blob([wbout], { type: 'application/octet-stream' }), '订单列表.xlsx');
                    } else {
                        // 在其他浏览器中使用file-saver保存文件
                        saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '订单列表.xlsx');
                    }
                } catch (e) {
                    if (typeof console !== 'undefined') console.log(e, wbout);
                }
                return wbout;
            }, 1000);
            setTimeout(() => {
                this.getData(1)
            }, 2000);
        },
        // 分页插件事件
        callFather(parm) {
            this.pageparm.page = parm.currentPage
            this.getData(parm.currentPage)
        },
        // 获取商品类别列表
        gteTypeData() {
            getCommodityCategoryList().then((res) => {
                this.loading = false;
                if (res.code != 200) {
                    this.$Message({
                        type: "info",
                        message: res.msg,
                    });
                } else {
                    res.data.list.forEach((item) => {
                        this.optionsType.push({ label: item.categoryName, value: item.id })
                    })
                    return console.log('this.optionsType', this.optionsType);;
                }
            })
        },
        // 搜索数据
        search() {
            if (this.startTimev != '') {
                this.timestamp = Math.floor(new Date(this.startTimev).getTime() / 1000)
            } if (this.endTimev != '') {
                this.timestampv = Math.floor(new Date(this.endTimev).getTime() / 1000)
            }
            this.getData(1)
        },
        // 重置数据
        chongzhi() {
            this.mobilev = ''
            this.orderNumberv = ''
            this.statusv = ''
            this.startTimev = ''
            this.timestamp = ''
            this.endTimev = ''
            this.timestampv = ''
            this.range = ''
            this.flagv = ''
            this.categoryIdv = ''
            this.getData(1)
        },
        // 是否实体
        isShiti: function (row) {
            if (row.entity == 0) {
                return "虚体"
            } else if (row.entity == 1) {
                return "实体"
            }
        },
        // 状态
        zhuangTai: function (row) {
            if (row.status == 0) {
                return "待支付"
            } else if (row.status == 1) {
                return "待发货"
            } else if (row.status == 2) {
                return "待收货"
            } else if (row.status == 3) {
                return "已完成"
            } else if (row.status == 4) {
                return "已关闭"
            }
        },
        // 价格类型
        PriceType: function (row) {
            if (row.shopPriceType == 0) {
                return "积分"
            } else if (row.shopPriceType == 1) {
                return "微信支付"
            } else if (row.shopPriceType == 2) {
                return "积分加微信支付"
            }
        },
        // 去发货
        tofahuo(row) {
            this.$confirm("确定发货吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "success",
            }).then(() => {
                let data = {
                    id: row.id,
                }
                tryPost(data).then(res => {
                    if (res.code == 200) {
                        this.$message.success(res.msg)
                        this.getData(this.pageparm.currentPage)
                    } else {
                        this.$message.error(res.msg)
                    }
                })

            }).catch((err) => {
                this.$message({
                    type: "info",
                    message: "已取消发货",
                });
            });
            return
            var userdata = JSON.parse(localStorage.getItem("userdata"))
            this.$prompt('请输入密码', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^(?!(\s+$))/,
                inputErrorMessage: '不可以空数据提交!'
            }).then(({ value }) => {
                if (value === userdata.menuTwo) {

                } else {
                    this.$message({
                        type: 'error',
                        message: '密码错误'
                    });
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消输入'
                });
            });
        },
        // 获取数据
        getData(page) {
            this.loading = true;
            let data = {
                mobile: this.mobilev,
                orderNumber: this.orderNumberv,
                status: this.statusv,
                startTime: this.timestamp,
                endTime: this.timestampv,
                categoryId: this.categoryIdv,
                flag: this.flagv,
                page: (page - 1) * 20,
            }
            getShopOrderList(data).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    this.productData = res.data.list;
                    this.pageparm.currentPage = page;
                    this.pageparm.total = res.data.count;
                    return;
                } else {
                    this.$Message({
                        type: "info",
                        message: res.msg
                    })
                }
            })
        }
    }
}
</script>

<style></style>